package com.doradance.app.home;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.common.pay.PayResult;
import com.doradance.entity.UpdataMemberEntity;
import com.doradance.entity.VipEntity;
import com.doradance.entity.WeChatEntity;
import com.pachong.android.baseuicomponent.fragment.BaseFragment;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.GsonUtils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.doradance.account.utils.WechatHelper.WECHAT_APP_ID;
import static com.doradance.wxapi.WXPayEntryActivity.WECHAR_PAY;
import static com.doradance.wxapi.WXPayEntryActivity.WECHAR_PAY_FAIL;

/**
 * A simple {@link Fragment} subclass.
 */
public class VipRechargeListFragment extends BaseFragment {
    @Bind(R.id.id_vipList)
    ListView mIdVipList;
    @Bind(R.id.tv_recharge_is)
    TextView mTvRechargeIs;
    private vipAdapter vipAdapter;
    private List<VipEntity.VipsBean> vips1;
    private Boolean isOpen1;
    private Boolean isHighest1;
    RadioButton rbWeixin;
    VipEntity.VipsBean vipsBean;
    RadioButton rbAli;
    private PayTask alipay;
    Dialog dialog;
    private IWXAPI msgApi;
    String name1;
    String type1;
    public VipRechargeListFragment() {
        // Required empty public constructor
    }

    @SuppressLint("ValidFragment")
    public VipRechargeListFragment(String name,List<VipEntity.VipsBean> vips, Boolean isOpen, Boolean isHighest,String type) {
        name1=name;
        vips1 = vips;
        isOpen1 = isOpen;
        isHighest1 = isHighest;
        type1 = type;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        vipAdapter = new vipAdapter(getContext(), vips1, isOpen1, isHighest1);
        msgApi = WXAPIFactory.createWXAPI(getContext(), null);
        // 将该app注册到微信
        msgApi.registerApp(WECHAT_APP_ID);
        //注册广播接收回调
        alipay = new PayTask(getActivity());
        PayReceiver payReceiver = new PayReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WECHAR_PAY);
        filter.addAction(WECHAR_PAY_FAIL);
        getContext().registerReceiver(payReceiver, filter);
        mIdVipList.setAdapter(vipAdapter);
        //开通会员
        vipAdapter.setOnItemOpenListener(new vipAdapter.onItemOpenListener() {
            @Override
            public void onOpenClick(int position) {
                initDialog(position);
            }
        });
        ButterKnife.bind(this, view);
        if(isOpen1 =true && isHighest1==false){
            mTvRechargeIs.setVisibility(View.VISIBLE);
            mTvRechargeIs.setText("您是"+name1+"会员等级，您可以选择以上会员升级哦！");

        }else if(isOpen1 =true && isHighest1==true){
            mTvRechargeIs.setVisibility(View.VISIBLE);
            mTvRechargeIs.setText("您当前已经是最高级会员，棒棒哒！");
        }
        return view;
    }

    //弹起dialog
    private View myView;

    private void initDialog(int position) {
        LayoutInflater factory = LayoutInflater.from(getContext());
        myView = factory.inflate(R.layout.select_pay_type, null);
        dialog = new AlertDialog.Builder(getContext(), R.style.quick_option_dialog)
                .setView(myView).create();
        //设置点击Dialog外部任意区域关闭Dialog
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        //设置弹窗在底部
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes(); //获取对话框当前的参数值
        p.width = d.getWidth(); //宽度设置为屏幕
        dialog.getWindow().setAttributes(p); //设置生效

        vipsBean = vips1.get(position);
        TextView tvPayName = (TextView) myView.findViewById(R.id.tv_pay_name);
        TextView tvPayPrice = (TextView) myView.findViewById(R.id.tv_pay_price);
        rbWeixin = (RadioButton) myView.findViewById(R.id.rb_weixin);
        rbAli = (RadioButton) myView.findViewById(R.id.rb_ali);
        rbWeixin.setChecked(true);
        tvPayName.setText(vips1.get(position).getName() + "VIP");
        tvPayPrice.setText("￥" + vips1.get(position).getPrice());

        myView.findViewById(R.id.rl_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!rbWeixin.isChecked() && !rbAli.isChecked()) {
                    EasyToast.showToast(getContext(), "请先选择支付方式");
                } else if (rbWeixin.isChecked()) {
                    pay(vipsBean.getId(), "wxpay");
                } else {
                    pay(vipsBean.getId(), "alipay");
                }
            }
        });

    }

    private void pay(int id, final String payType) {
        MyHttpRequest request = new MyHttpRequest(getContext());
        JSONObject job = new JSONObject();
        try {
            job.put("vip_id", id);
            job.put("pay_type", payType);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.post(UrlCenter.PAY_VIP, job, new DataRequestListener<String>(String.class) {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                dialog.cancel();
                if (payType.equals("wxpay")) {
                    WeChatEntity weChatEntity = GsonUtils.string2Object(o, WeChatEntity.class);
                    onStartWechatPay(weChatEntity);
                } else {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(o);
                        String value = jsonObject.getString("value");
                        startAliPay(value);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Log.e("ooo", strMsg);
            }
        });

    }

    //支付宝支付
    private void startAliPay(final String value) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                // 调用支付接口，获取支付结果
                String result = alipay.pay(value);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                alipayHanlder.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private AlipayHanlder alipayHanlder = new AlipayHanlder();

    private class AlipayHanlder extends Handler {
        @Override
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((String) msg.obj);
            String resultStatus = payResult.getResultStatus();
            String result = payResult.getResult();
            Log.e("payResult", resultStatus);
            if (resultStatus.equals("9000")) {
                Toast.makeText(getContext(), "支付成功",
                        Toast.LENGTH_SHORT).show();
                getActivity().finish();
                VipRechargeActivity.start(getActivity(),type1);
                if(!type1.equals(-1)){
                    CoursesDetailActivity a = new CoursesDetailActivity();
                    a.CoursesDetailActivity.finish();
                }

            } else {
                // 判断resultStatus 为非“9000”则代表可能支付失败
                // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                if (resultStatus.equals("8000")) {
                    Toast.makeText(getContext(), "支付结果确认中",
                            Toast.LENGTH_SHORT).show();

                } else {
                    // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                    Toast.makeText(getContext(), "支付失败",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //微信支付
    private void onStartWechatPay(WeChatEntity wechatPayEntity) {
        PayReq request = new PayReq();
        //微信分配的公众账号ID
        request.appId = wechatPayEntity.getAppid();
        //微信支付分配的商户号
        request.partnerId = wechatPayEntity.getPartnerid();
        //微信返回的支付交易会话ID
        request.prepayId = wechatPayEntity.getPrepayid();
        //暂填写固定值Sign=WXPay
        request.packageValue = wechatPayEntity.getPackageX();
        //随机字符串，不长于32位。推荐随机数生成算法
        request.nonceStr = wechatPayEntity.getNoncestr();
        //时间戳，请见接口规则-参数规定
        request.timeStamp = wechatPayEntity.getTimestamp();
        //签名，详见签名生成算法
        request.sign = wechatPayEntity.getSign();
        msgApi.sendReq(request);

    }

    /**
     * 微信成功回调广播
     */
    private class PayReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WECHAR_PAY.equals(action)) {
                Log.e("1111111111","111111758757");
                EasyToast.showToast(getContext(), "支付成功");
                getActivity().finish();
                VipRechargeActivity.start(getActivity(),type1);
//                if(!type1.equals(-1)){
//                    CoursesDetailActivity a = new CoursesDetailActivity();
//                    a.CoursesDetailActivity.finish();
//                }
            } else {
                EasyToast.showToast(getContext(), "支付失败");
            }
        }
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.vip_recharge_fragment, null);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
